<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-date-picker
            v-model="query.dateRange"
            type="datetimerange"
            :shortcuts="shortcuts"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="defaultTime"
        />
        <!--        <el-input v-model="query.parkingName" placeholder="车场名称" clearable/>-->
        <el-input v-model="query.carNumber" placeholder="车牌号" clearable/>
        <el-input v-model="query.carOwer" placeholder="车主姓名" clearable/>
        <el-input v-model="query.phoneNum" placeholder="电话" clearable/>
        <el-input v-model="query.address" placeholder="地址" clearable/>
        <el-select
            v-model="query.parkingName"
            placeholder="请选择车场"
            filterable
            @change="(val:any)=>handleQuerySelectChange('cityId',val)"
        >
          <el-option
              v-for="item in selectsData.parking_select"
              :key="item.parkingName"
              :label="item.cityName + ' - ' + item.parkingName"
              :value="item.parkingName"
          />
        </el-select>
        <!--        <el-select v-model="query.carStatus" placeholder="车辆状态" clearable>-->
        <!--          <el-option-->
        <!--              v-for="item in selectsData.status_select"-->
        <!--              :key="item.value"-->
        <!--              :label="item.label"-->
        <!--              :value="item.value"-->
        <!--          />-->
        <!--        </el-select>-->
        <el-select v-model="query.carTimeStatus" placeholder="状态" clearable>
          <el-option
              v-for="item in selectsData.time_status_select"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <el-button type="primary" :icon="Search" @click="handleSearch">
        </el-button>
        <el-button @click="handleClear">重置</el-button>
      </div>
      <div class="handle-box">
        <el-button type="primary" :icon="Plus" @click="handleEdit()" style="margin-right: 10px">添加</el-button>
        <el-button link @click="download('car.xlsx','车辆列表模板')">车辆列表模板下载</el-button>
        <!--        <el-upload-->
        <!--            style="margin-left: 12px"-->
        <!--            class="upload-demo"-->
        <!--            :auto-upload="false"-->
        <!--            :multiple="false"-->
        <!--            :show-file-list="false"-->
        <!--            :accept="'.xls, .xlsx'"-->
        <!--            @change="handleOfUpload"-->
        <!--        >-->
        <!--          <el-button type="primary">批量导入</el-button>-->
        <!--        </el-upload>-->
        <el-button type="primary" @click="batchAddVisible = true">批量导入</el-button>
        <el-button :disabled="!multipleSelection.length" @click="handleChangeItem(multipleSelection,'batchDel')">批量删除
        </el-button>
        <el-button @click="handleOfExport">导出全部</el-button>
      </div>
      <el-table
          :data="tableData"
          max-height="calc(100vh - 250px)"
          border
          class="table"
          @selection-change="handleSelectionChange"
          header-cell-class-name="table-header">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="parkingName" label="停车场名称" align="center" min-width="120">
          <template #default="scope">
            <span :data-city-name="scope.row?.cityName">{{ scope.row.parkingName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="carNumber" label="车牌号" align="center" min-width="100"></el-table-column>
        <el-table-column prop="carOwer" label="车主姓名" align="center" min-width="100"></el-table-column>
        <el-table-column prop="phoneNum" label="电话" align="center" min-width="120"></el-table-column>
        <el-table-column prop="carStatus" label="状态" align="center">
          <template #default="scope">
            <!--            <template v-if="$moment(scope.row.endTime).isAfter($moment())">-->
            <!--              <el-switch-->
            <!--                  :model-value="scope.row.carStatus == 1"-->
            <!--                  inline-prompt-->
            <!--                  active-text="启用"-->
            <!--                  inactive-text="停用"-->
            <!--                  @change="(val:any)=>handleOfChange({-->
            <!--                  ...scope.row,-->
            <!--                  carStatus: val ? '1' : '0'-->
            <!--                },'carStatus')"-->
            <!--              />-->
            <!--            </template>-->
            <el-tag v-if="$moment(scope.row.endTime).isAfter($moment())">正常</el-tag>
            <el-tag v-else type="info">过期</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" align="center" min-width="180">
          <template #default="scope">
            <span>{{ $moment(scope.row.startTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" align="center" min-width="180">
          <template #default="scope">
            <span>{{ $moment(scope.row.endTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址" align="center" min-width="100"></el-table-column>
        <el-table-column prop="ps" label="备注" align="center" min-width="100"></el-table-column>
        <el-table-column label="操作" align="center" width="160" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small"
                       @click="handleEdit(scope.row)"
            >编辑
            </el-button>
            <el-button type="danger" size="small"
                       @click="handleChangeItem(scope.row, 'del')">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
            hide-on-single-page
            v-model:current-page="query.page"
            v-model:page-size="query.pageSize"
            background
            :page-sizes="[10, 20, 30, 40, 50, 100, 200]"
            layout="prev, pager, next, jumper, total, sizes"
            :total="pageTotal"
            @current-change="handlePageChange"
            @size-change="handleLimitChange"
        ></el-pagination>
      </div>
    </div>
    <!--    添加/编辑弹框-->
    <el-dialog v-model="dialogVisible" destroy-on-close
               :title="batchAddVisible ? '批量添加车辆' : (addVisible ? '添加车辆' : '编辑车辆')"
               width="50%"
               draggable>
      <el-form
          label-width="auto"
          ref="ruleFormRef"
          :model="editform"
          :rules="rules"
      >
        <template v-if="batchAddVisible">
<!--          <el-form-item label="小区名称" prop="cityId">-->
<!--            <el-select-->
<!--                v-model="editform.cityId"-->
<!--                placeholder="请选择项目（小区）"-->
<!--                filterable-->
<!--            >-->
<!--              <el-option-->
<!--                  v-for="item in selectsData.object_select"-->
<!--                  :key="item.id"-->
<!--                  :label="item.cityName"-->
<!--                  :value="item.id"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item label="车场信息" prop="parkingId">
            <el-select
                v-model="editform.parkingId"
                placeholder="请选择车场信息"
                filterable
                @change="(val:any)=>handleEditformSelectChange('cityId',val)"
            >
              <el-option
                  v-for="item in selectsData.parking_select"
                  :key="item.id"
                  :label="item.cityName + ' - ' + item.parkingName"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
        <template v-else>
<!--          <el-form-item label="车场名称" prop="parkingName">-->
<!--            <el-select-->
<!--                v-model="editform.parkingName"-->
<!--                placeholder="请选择车场"-->
<!--                filterable-->
<!--                @change="(val:any)=>handleEditformSelectChange('cityId',val)"-->
<!--            >-->
<!--              <el-option-->
<!--                  v-for="item in selectsData.parking_select"-->
<!--                  :key="item.parkingName"-->
<!--                  :label="item.cityName + ' - ' + item.parkingName"-->
<!--                  :value="item.parkingName"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item label="车场名称" prop="parkingId">
            <el-select
                v-model="editform.parkingId"
                placeholder="请选择车场"
                filterable
                @change="(val:any)=>handleEditformSelectChange('cityId',val)"
            >
              <el-option
                  v-for="item in selectsData.parking_select"
                  :key="item.id"
                  :label="item.cityName + ' - ' + item.parkingName"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="车牌号" prop="carNumber">
            <el-input v-model="editform.carNumber" placeholder="请输入车牌号"></el-input>
          </el-form-item>
          <el-form-item label="时间区间" prop="dateRange">
            <el-date-picker
                v-model="editform.dateRange"
                type="datetimerange"
                :shortcuts="shortcuts"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="defaultTime"
            />
          </el-form-item>
          <el-form-item label="车主姓名" prop="carOwer">
            <el-input v-model="editform.carOwer" placeholder="请输入车主姓名"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phoneNum">
            <el-input v-model="editform.phoneNum" placeholder="请输入电话"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="editform.address" placeholder="请输入地址"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="ps">
            <el-input v-model="editform.ps" placeholder="请输入备注"></el-input>
          </el-form-item>
          <!--        <el-form-item label="状态" prop="carStatus">-->
          <!--          <el-radio-group v-model="editform.carStatus">-->
          <!--            <el-radio v-for="item in selectsData.status_select" :label="item.value">{{ item.label }}</el-radio>-->
          <!--          </el-radio-group>-->
          <!--        </el-form-item>-->
        </template>
      </el-form>
      <template #footer>
          <span class="dialog-footer">
          <el-upload
              :disabled="!editform.cityId"
              v-if="batchAddVisible"
              style="margin-left: 12px"
              class="upload-demo"
              :auto-upload="false"
              :multiple="false"
              :show-file-list="false"
              :accept="'.xls, .xlsx'"
              @change="handleOfUpload"
          >
              <el-button type="primary" :disabled="!editform.cityId">批量导入</el-button>
            </el-upload>
            <template v-else>
            <el-button type="primary" @click="saveItem(ruleFormRef)">立即提交</el-button>
            <el-button @click="handleEditClear()">重置</el-button>
              </template>
          </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="parkingCar">
import {ref, reactive, computed, watch} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Delete, Edit, CopyDocument, Search, Plus} from '@element-plus/icons-vue';
import type {FormInstance, FormRules} from 'element-plus'
import {ParkingMgt} from "@/api";
import {useRoute, useRouter} from "vue-router"
import useClipboard from 'vue-clipboard3';
import moment from 'moment';
import * as XLSX from 'xlsx/xlsx.mjs';
// import excelDom from '@/assets/template/car.xlsx?url';
import {useMenuStore} from "@/store/menu";

const menu = useMenuStore();
const $moment = moment
defineExpose({
  $moment
})

const {toClipboard} = useClipboard();
const copy = async (text) => {
  try {
    await toClipboard(text);  //实现复制
    ElMessage.success('复制成功')
  } catch (e) {
    console.error(e);
  }
};

interface TableItem {
  id?: string;
}

const download = (filename, name) => {
  let a = document.createElement('a');
  a.href = '/' + filename;
  //路径中'/'为根目录，即index.html所在的目录
  a.download = name;
  console.log(a)
  // a.click();
  window.open(a.href)
}

const query = reactive({
  cityId: undefined,
  parkingName: undefined,
  carNumber: undefined,
  carOwer: undefined,
  phoneNum: undefined,
  address: undefined,
  carStatus: undefined,
  carTimeStatus: undefined,
  dateRange: [],
  page: 1,
  pageSize: 10
});

const reset = () => {
  query.cityId = undefined;
  query.parkingName = undefined;
  query.carNumber = undefined;
  query.carOwer = undefined;
  query.phoneNum = undefined;
  query.address = undefined;
  query.carStatus = undefined;
  query.carTimeStatus = undefined;
  query.dateRange = [];
  query.page = 1;
  query.pageSize = 10;
};

const useFormatOrGetDefaultDateByMoment = date => date ? moment(date).format('YYYY-MM-DD HH:mm:ss') : moment().format('YYYY-MM-DD 00:00:00')

const handleOfUpload = (e: any) => {
  console.log(e);
  // debugger
  const file = e.raw;
  const reader = new FileReader();
  reader.readAsBinaryString(file)// 将文件以二进制形式读入页面
  reader.onload = (e) => {
    const data = e.target.result; //读取成功后result中的数据
    const wb = XLSX.read(data, {type: 'binary', cellDates: true});  //以base64方法读取 结果
    const sheetName = wb.SheetNames[0] //是获取Sheets中第一个Sheet的名字
    const sheets = wb.Sheets[sheetName] //wb.Sheets[Sheet名]获取第一个Sheet的数据
    //将数据解析为json字符串
    const dataList2 = JSON.stringify(XLSX.utils.sheet_to_json(sheets))
    const dataList3 = (JSON.parse(dataList2)) //讲json转为 数组的格式 看格式所需
    const parkingNames = dataList3.map(item => {
      return {
        // parkingName: item.车场名称,
        carNumber: item.车牌号,
        startTime: useFormatOrGetDefaultDateByMoment(item.开始时间),
        endTime: useFormatOrGetDefaultDateByMoment(item.结束时间),
        carOwer: item.车主名称,
        phoneNum: item.电话,
        address: item.地址,
        ps: item.备注,
        // carStatus: item.状态 === '禁用' ? '0' : '1',
      }
    })

    console.log(parkingNames);
    batchAddParking(parkingNames, (res: any) => {
      if (res.data.status === 1) {
        if (editVisible.value) editVisible.value = false;
        if (addVisible.value) addVisible.value = false;
        if (batchAddVisible.value) batchAddVisible.value = false;
        ElMessage.success(res.data.msg);
        getData();
      } else {
        ElMessage.error(res.data.msg);
      }
    })
    console.log(dataList3);
  };
  // reader.onload = async function (e) {
  //   console.log(e);
  //   // 解析数据
  //   let context = await XLSX.read(e.target.result, {type: "binary"});
  //   //XLSX.utils.sheet_to_json()解析excel，给空的单元格赋值为空字符串
  //   let excel = await XLSX.utils.sheet_to_json(
  //       context.Sheets[context.SheetNames[0]]
  //   );
  //   console.log(excel);
  // };
  // reader.readAsBinaryString(file);
}

const tableData = ref<TableItem[]>([]);
const pageTotal = ref(0);
// 获取表格数据
const getData = () => {
  const params = {
    ...query,
    startTime: query.dateRange?.[0],
    endTime: query.dateRange?.[1]
  };
  delete params.dateRange;
  ParkingMgt.getParkingCarList(params).then((res: any) => {
    tableData.value = res.data.data?.list || [];
    pageTotal.value = res.data.data?.total || res.data.data?.list?.length || 10;
  });
};
const route = useRoute();
const localQuery = menu.getQueryData(route.path);
if (route.query || localQuery) {
  const resQuery = {...localQuery, ...route.query}
  for (let i in resQuery) {
    if (query.hasOwnProperty(i) && resQuery[i] !== undefined) {
      query[i] = resQuery[i];
    }
  }
}
getData();

const selectsData: any = ref({
  object_select: [],
  time_status_select: [
    {label: "正常", value: '1'},
    {label: "过期", value: '0'}
  ],
  car_status_select: [
    {label: "启用", value: '1'},
    {label: "停用", value: '0'}
  ]
});

const getSelectData = () => {
  ParkingMgt.getProjectItemList({page: -1}).then((projectRes: any) => {
    ParkingMgt.getParkingItemList({page: -1}).then((parkingRes: any) => {
      selectsData.value = {
        ...selectsData.value,
        parking_select: parkingRes.data.data?.list || [],
        object_select: projectRes.data.data?.list || []
      }
    });
  });
};
getSelectData();

const multipleSelection = ref<TableItem[]>([])
const handleSelectionChange = (val: TableItem[]) => {
  multipleSelection.value = val
}

const handleOfChange = (params: any, type: string, needMsgBox = true) => {
  let themTxt = '', api;
  if (type === 'carStatus') {
    themTxt = '确定要修改车辆状态吗'
    api = ParkingMgt.updateParkingCar;
  }
  if (needMsgBox) {
    ElMessageBox.confirm(`${themTxt}`, '提示', {
      type: 'warning'
    }).then(() => {
      api(params).then((res: any) => {
        if (res.data.status === 1) {
          getData();
          ElMessage.success('修改成功！');
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    }).catch(() => {
    });
  } else {
    api(params).then((res: any) => {
      if (res.data.status === 1) {
        getData();
        ElMessage.success('修改成功！');
      } else {
        ElMessage.error(res.data.msg);
        getData();
      }
    })
  }
};

const handleSearch = () => {
  getData();
};

const handleClear = () => {
  reset();
  ElMessage.success("重置成功！");
  getData();
};

const handlePageChange = (val: number) => {
  query.page = val;
  getData();
};

watch(() => query.page, (newVal, oldVal) => {
  menu.setQueryData({key: route.path, data: {page: newVal}});
})

const handleLimitChange = (val: number) => {
  query.page = 1;
  query.pageSize = val;
  getData();
};

const editVisible = ref(false);
const addVisible = ref(false);
const batchAddVisible = ref(false);
let editform = reactive<any>(({
  cityId: undefined,
  parkingId: undefined,
  parkingName: '',
  carNumber: '',
  carOwer: '',
  phoneNum: '',
  address: '',
  carStatus: '1',

  dateRange: "",
  startTime: '',
  endTime: '',

  ps: '',
}));

const defaultTime = [
  $moment(new Date()).startOf("day").format('YYYY-MM-DD HH:mm:ss'),
  $moment(new Date()).endOf("day").format('YYYY-MM-DD HH:mm:ss')
];

const shortcuts = [
  {
    text: '一周',
    value: () => {
      const start = $moment(new Date()).startOf("day").format('YYYY-MM-DD HH:mm:ss');
      const end = $moment(new Date()).add(1, 'week').endOf("day").format('YYYY-MM-DD HH:mm:ss')
      return [start, end]
    },
  },
  {
    text: '一月',
    value: () => {
      const start = $moment(new Date()).startOf("day").format('YYYY-MM-DD HH:mm:ss');
      const end = $moment(new Date()).add(1, 'month').endOf("day").format('YYYY-MM-DD HH:mm:ss')
      return [start, end]
    },
  },
  {
    text: '一年',
    value: () => {
      const start = $moment(new Date()).startOf("day").format('YYYY-MM-DD HH:mm:ss');
      const end = $moment(new Date()).add(1, 'year').endOf("day").format('YYYY-MM-DD HH:mm:ss')
      return [start, end]
    },
  },
  {
    text: '三年',
    value: () => {
      const start = $moment(new Date()).startOf("day").format('YYYY-MM-DD HH:mm:ss');
      const end = $moment(new Date()).add(3, 'year').endOf("day").format('YYYY-MM-DD HH:mm:ss')
      return [start, end]
    },
  },
  {
    text: '五年',
    value: () => {
      const start = $moment(new Date()).startOf("day").format('YYYY-MM-DD HH:mm:ss');
      const end = $moment(new Date()).add(5, 'year').endOf("day").format('YYYY-MM-DD HH:mm:ss')
      return [start, end]
    },
  },
  {
    text: '十年',
    value: () => {
      const start = $moment(new Date()).startOf("day").format('YYYY-MM-DD HH:mm:ss');
      const end = $moment(new Date()).add(10, 'year').endOf("day").format('YYYY-MM-DD HH:mm:ss')
      return [start, end]
    },
  },
]

const handleQuerySelectChange = (key: string, value: any) => {
  if (key === 'cityId') {
    query.cityId = (selectsData.value.parking_select || []).find((item: any) => item.parkingName == value)?.cityId;
  }
}

const handleEditformSelectChange = (key: string, value: any) => {
  if (key === 'cityId') {
    editform.cityId = (selectsData.value.parking_select || []).find((item: any) => (item.id == value))?.cityId;
    editform.parkingName = (selectsData.value.parking_select || []).find((item: any) => (item.id == value))?.parkingName;
  }
}

// const
const handleEdit = (row?: any) => {
  handleEditClear(true);
  if (row) {
    editVisible.value = true;
    for (const key in row) {
      if (row[key] !== undefined && editform.hasOwnProperty(key)) {
        editform[key] = row[key];
      }
    }
    editform.dateRange = [row.startTime, row.endTime]
    editform.id = row.id;
  } else {
    addVisible.value = true;
  }
};

const handleEditClear = (clearAll?: boolean) => {
  for (const key in editform) {
    if (!clearAll && key === 'id') continue;
    if (key === 'carStatus') {
      editform[key] = '1';
    } else {
      editform[key] = '';
    }
  }
};

const dialogVisible = computed({
  get: () => !!(addVisible.value || editVisible.value || batchAddVisible.value),
  set: (val) => {
    addVisible.value = val;
    editVisible.value = val;
    batchAddVisible.value = val;
  }
});

const siteSelection = computed({
  get: () => {
    if (addVisible.value) {
      return editform.web_ids || []
    } else {
      return {key: editform.web_id}
    }
  },
  set: (val: any) => {
    editform.web_name = '';
    addVisible.value ? (editform.web_ids = val) : (editform.web_id = val.key);
  }
})

const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  cityId: [{
    required: true, message: '请选择项目（小区）名称！', trigger: 'change'
  }],
  parkingId: [{
    required: true, message: '请选择车场信息！', trigger: 'change'
  }],
  parkingName: [{
    required: true, message: '请选择车场名称！', trigger: 'change'
  }],
  carNumber: [{
    required: true, message: '请输入车牌号！', trigger: 'blur'
  }],
  dateRange: [{
    required: true, message: '请选择时间区间！', trigger: 'change'
  }],
  carOwer: [{
    required: true, message: '请输入车主姓名！', trigger: 'blur'
  }],
  phoneNum: [{
    required: true, message: '请输入手机号！', trigger: 'blur'
  }],
  carStatus: [{required: true, message: '请选择车辆状态！', trigger: 'change'}]
})

const batchAddParking = (data, callback) => {
  const params = {
    license: [...data],
    cityId: editform.cityId,
    parkingId: editform.parkingId,
  }
  ParkingMgt.batchAddParkingCar({...params}).then((res: any) => {
    console.log(res, 'res')
    callback(res)
  })
}

const saveItem = async (formEl: FormInstance | undefined) => {
  if (formEl) {
    const valid = await formEl.validate((valid, fields) => valid);
    if (!valid) return;
  }

  let apiFun, params: any = {}
  if (addVisible.value) {
    // apiFun = ParkingMgt.addParkingCar;
    // params = {
    //   carData: [{
    //     ...editform,
    //     startTime: editform.dateRange[0],
    //     endTime: editform.dateRange[1],
    //     dateRange: undefined
    //   }]
    // }
    params = [{
      ...editform,
      startTime: editform.dateRange[0],
      endTime: editform.dateRange[1],
      dateRange: undefined
    }]

    batchAddParking(params, (res: any) => {
      if (res.data.status === 1) {
        if (editVisible.value) editVisible.value = false;
        if (addVisible.value) addVisible.value = false;
        if (batchAddVisible.value) batchAddVisible.value = false;
        ElMessage.success(res.data.msg);
        getData();
      } else {
        ElMessage.error(res.data.msg);
      }
    })

    return;
  } else if (editVisible.value) {
    apiFun = ParkingMgt.updateParkingCar;
    params = {
      ...editform,
      startTime: editform.dateRange[0],
      endTime: editform.dateRange[1]
    }
    delete params.dateRange;
  }
  if (!apiFun) return;
  apiFun({...params}).then((res: any) => {
    if (res.data.status === 1) {
      addVisible.value && (addVisible.value = false);
      editVisible.value && (editVisible.value = false);
      ElMessage.success(res.data.msg);
      getData();
    } else {
      ElMessage.error(res.data.msg);
    }
  })
}

const exportList = (arr: any) => {
  let tableData = [
    ['车场名称', '车牌号', '开始时间', '结束时间', '车主名称', "电话", "地址", "备注", "状态"]//导出表头
  ] // 表格表头
  arr.forEach((item, index) => {
    let rowData = []
    //导出内容的字段
    rowData = [
      item.parkingName,
      item.carNumber,
      moment(item.startTime).format('YYYY-MM-DD HH:mm:ss'),
      moment(item.endTime).format('YYYY-MM-DD HH:mm:ss'),
      item.carOwer,
      item.phoneNum,
      item.address,
      item.ps,
      moment(item.endTime).isAfter(moment()) ? '' : '过期',
    ]
    tableData.push(rowData)
  })
  let workSheet = XLSX.utils.aoa_to_sheet(tableData);
  let bookNew = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(bookNew, workSheet, '车辆列表') // 工作簿名称
  let name = '车辆列表' + moment(new Date()).format('YYYY-MM-DD HHmmss') + '.xlsx'
  XLSX.writeFile(bookNew, name) // 保存的文件名
}

const handleOfExport = () => {
  ElMessageBox.confirm(`确定要导出全部车辆吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ParkingMgt.exportParkingCar({}).then((res: any) => {
      if (res.data.status === 1) {
        exportList(res.data.data?.data || []);
      } else {
        ElMessage.error(res.data.msg);
      }
    })
  }).catch(() => {
  });
}

const handleChangeItem = (data: any, type: string) => {
  let contTxt = '', themeTxt = '', apiFun: any = '', apiParams: any = {};
  if (type === 'del') {
    contTxt = '删除车辆'
    themeTxt = ' ' + data.carNumber + ' ';
    apiFun = ParkingMgt.deleteParkingCar;
    // apiParams = {ids: [data.id]}
    apiParams = {
      ids: [{
        id: data.id,
        parkingId: data.parkingId
      }]
    }
  } else if (type === 'batchDel') {
    contTxt = '删除选中的车辆'
    apiFun = ParkingMgt.deleteParkingCar;
    // apiParams = {ids: data.map(item => item.id)}
    apiParams = {
      ids: data.map(item => {
        return {
          id: item.id,
          parkingId: item.parkingId
        }
      })
    }
  }
  if (!apiFun) return;
  ElMessageBox.confirm(`确定要${contTxt + themeTxt}吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    apiFun(apiParams).then((res: any) => {
      if (res.data.status === 1) {
        ElMessage.success(res.data.msg);
        getData();
      } else {
        ElMessage.error(res.data.msg);
      }
    })
  })
      .catch(() => {
      });
};

</script>

<style lang="less" scoped>
.handle-box {
  display: flex;
  flex-wrap: wrap;

  :deep(.el-date-editor),
  .el-select,
  .el-input {
    margin-right: 10px;
    min-width: 350px;
    flex: 1;
  }

  :deep(.el-date-editor),
  .el-select,
  .el-input,
  .el-upload,
  .el-button {
    margin-bottom: 10px;
  }

  :deep(.responseTime) {
    margin-right: 10px;
    //min-width: 350px;
    flex: 1;
    display: flex;
    align-items: center;

    .startTime,
    .endTime {
      flex: 1;
      margin-right: 0px;
    }

    .startTime {
      .el-input__wrapper {
        border-radius: 0;
      }
    }

    .endTime {
      .el-input-group__prepend {
        border-radius: 0;
        box-shadow: 0px 0 0 0 var(--el-input-border-color) inset, 0 1px 0 0 var(--el-input-border-color) inset,0 -1px 0 0 var(--el-input-border-color) inset;
      }
    }

  }
}

.el-table {
  .resultItem {
    color: inherit;
    cursor: pointer;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

    &:hover {
      color: #20a0ff;
    }
  }

  :deep(.el-switch__core) {
    width: 55px;
  }

  .btns {
    display: flex;
    justify-content: center;
  }
}

.el-dialog {
  .el-select {
    width: 100%;
  }

  .tip {
    color: red;
  }
}
</style>
